package com.atguigu.jedis;

import redis.clients.jedis.Jedis;

import java.util.Random;

/**
 * @author: 叶子
 * @date: 2022/04/23 21:47
 * 手机验证码功能，6位随机数字，2分钟有效，每个手机号每天只能输入3次
 **/
public class PhoneCode {
    public static void main(String[] args) {
//模拟验证码发送
        sendCode("13207831617");
        verifyCode("13207831617", "492445");
    }

    //1.生成6位数字验证码
    public static String getCode() {
        Random random = new Random();
        String code = "";
        for (int i = 0; i < 6; i++) {
            int rand = random.nextInt(10);
            code += rand;
        }
        return code;
    }

    //2.每个手机每天只能发送三次，验证码放到redis中，设置过期时间
    public static void sendCode(String phone) {
        //连接redis
        Jedis jedis = new Jedis("192.168.126.128", 6379);
        //拼接key

        //手机发送次数key
        String countKey = "VerifyCode" + phone + ":count";
        //验证码key
        String codeKey = "VerifyCode" + phone + ":code";
        //每个手机每天只能发送3次
        String count = jedis.get(countKey);
        if (count == null) {
            //没有发送次数，第一次发送
            jedis.setex(countKey, 24 * 60 * 60, "1");
            System.out.println("这是今天第1次发送验证码");
        } else if (Integer.parseInt(count) <= 2) {
            //发送次数+1
            jedis.incr(countKey);
            System.out.println("今天已经发送：" + Integer.parseInt(count) + "次验证码");
        } else if (Integer.parseInt(count) > 2) {
            System.out.println("今天发送次数已经超过3次");
            jedis.close();
            return;
        }
        //发送的验证码放到redis中
        String verifyCode = getCode();
        jedis.setex(codeKey, 120, verifyCode);
        jedis.close();
    }

    //3.验证码校验
    public static void verifyCode(String phone, String code) {
        String redisCode = "";
        //从redis中获取验证码
        Jedis jedis = new Jedis("192.168.126.128", 6379);
        //验证码key
        String codeKey = "VerifyCode" + phone + ":code";

        redisCode = jedis.get(codeKey);
        //判断
        if (null == redisCode) {
            System.out.println("验证码失效,验证失败");
        } else if (code.equals(redisCode)) {
            System.out.println("验证成功");
        } else {
            System.out.println("验证码不正确，验证失败");
        }

        jedis.close();
    }
}